function rstruct = renamefields(istruct, ffrom, fto)
% renamefields  - renames fields in a struct
%
% FORMAT:       renamed = renamefields(istruct, ffrom, fto)
%
% Input fields:
%
%       istruct     input structure array
%       ffrom       from field names cell array
%       fto         to field names cell array
%
% See also rmfield.

% Version:  v0.6e
% Build:    7041710
% Date:     Apr-17 2007, 10:02 AM CEST
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 3 || ...
   ~isstruct(istruct) || ...
   ~iscell(ffrom) || ...
   ~iscell(fto) || ...
    isempty(istruct) || ...
    numel(ffrom) ~= numel(fto)
    error( ...
        'BVQXtools:BadArgument', ...
        'Bad or too few arguments passed.' ...
    );
end

% get input sizes
flds = fieldnames(istruct);
nfld = length(flds);
sstr = size(istruct);
nstr = prod(sstr);

% get field sizes
ffrom = ffrom(:);
fto   = fto(:);
nflds = length(ffrom);

% remove unknown/bad fields
for fc = nflds:-1:1
    if ~ischar(ffrom{fc}) || ...
       ~ischar(fto{fc})
        ffrom(fc) = [];
        fto(fc)   = [];
        continue;
    end
    ffrom{fc} = ffrom{fc}(:)';
    fto{fc}   = fto{fc}(:)';
    if ~isrealvarname(ffrom{fc}) || ...
       ~isrealvarname(fto{fc}) || ...
        strcmp(ffrom{fc}, fto{fc}) || ...
       ~isfield(istruct, ffrom{fc})
        ffrom(fc) = [];
        fto(fc)   = [];
        continue;
    end
end
nflds = length(ffrom);
if nflds == 0
    rstruct = istruct;
    return;
end

% build lookup structs
fstruct = struct;
for fc = 1:nflds
    fstruct.(ffrom{fc}) = fc;
end
nstruct = struct;
for fc = 1:nfld
    if isfield(fstruct, flds{fc})
        nstruct.(flds{fc}) = true;
    else
        nstruct.(flds{fc}) = false;
    end
end

% build output structure
rstruct = struct;

% build output size argument if needed
if any(sstr > 1)
    osize = sprintf('%.0f,', sstr);
    eval(['rstruct(' osize(1:end-1) ')=rstruct;']);
end

% do the work
for sc = 1:nstr
    for fc = 1:nfld
        if nstruct.(flds{fc})
            rstruct(sc).(fto{fstruct.(flds{fc})}) = istruct(sc).(flds{fc});
        else
            rstruct(sc).(flds{fc}) = istruct(sc).(flds{fc});
        end
    end
end
